#    This file is part of robo-ircbot.
#
#    robo-ircbot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    robo-ircbot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with robo-ircbot.  If not, see <http://www.gnu.org/licenses/>.

package App::Modular::Module::Kernel;
use strict;
use warnings;
use XML::RSS;
use LWP::Simple;
use base qw(App::Modular::Module);

print ":: Linux Kernel module loaded.\n";

# Events we want to receive.
sub events { return "PRIVMSG"; }

sub help {
        return (
                "Show the latest mainline, 2.6, and 2.4 kernel versions.",
                "kernel"
        );
}

# PRIVMSG events.
sub event_privmsg
{
        shift;
        my $e = shift;

        my $help = $e->robo->mod("Helper") || return;

        # Admin commands for Kernel module.
        if ($help->trigger_switch("kernel", $e)) {
                return;
        }

        # Kernel trigger. Bngbng bng.
        if (my $h = $help->trig("kernel", $e)) {
                read_kernel($e);
        }
}

# Read the kernel.org RSS feed. Word.
sub read_kernel
{
        my $e = shift;

        # Download the rss content:
        # The get() function downloads any text file from the web
        # and will store it in a variable. Incredible.
        my $content = get("http://kernel.org/kdist/rss.xml");

        # Parse the RSS feed
        my $rss = new XML::RSS;
        $rss->parse($content);

        my $got26 = 0;
        my $got24 = 0;

        foreach my $item (@{$rss->{items}}) {
                if ((!$got26 && $item->{'title'} =~ /^(2\.6)\.(\d+\.?\d*)\: stable$/) ||
                    (!$got24 && $item->{'title'} =~ /^(2\.4)\.(\d+\.?\d*)\: stable$/)) {
                        $got26 = 1 if ($1 eq "2.6");
                        $got24 = 1 if ($1 eq "2.4");

                        $e->s("PRIVMSG ".$e->dest." :\002$item->{'title'}\002");
                        sleep(1);

                        $e->s("PRIVMSG ".$e->dest." :  \002(\002Link\002)\002 http://www.kernel.org/pub/linux/kernel/v$1/linux-$1.$2.tar.bz2");
                        sleep(1);

                        $e->s("PRIVMSG ".$e->dest." :  \002(\002Changelog\002)\002 http://www.kernel.org/pub/linux/kernel/v$1/ChangeLog-$1.$2");
                } elsif ($item->{'title'} =~ /mainline/) {
                        $e->s("PRIVMSG ".$e->dest." :\002$item->{'title'}\002");
                }
        }
}

1;

